Class Python Demos

I will be using this Notebook for class demos. To use at home, load Anaconda (https://www.continuum.io/downloads) or WinPython (https://winpython.github.io/)

Set() demo

First let's create a random list using the numpy library.


In [1]:
import numpy as np
nums1 = np.random.randint(1,11, 15)
nums1


Out[1]:
array([10,  4,  4,  2, 10, 10,  8,  5,  3,  4,  7,  7,  9,  7,  8])

Let's look at what set() does!


In [2]:
set1 = set(nums1)
set1


Out[2]:
{2, 3, 4, 5, 7, 8, 9, 10}

Let's create a 2nd list and set.


In [3]:
nums2 = np.random.randint(1,11, 12)
nums2


Out[3]:
array([ 4,  2,  6,  4, 10,  2,  5,  2,  1,  7,  4,  4])

In [4]:
set2 = set(nums2)
set2


Out[4]:
{1, 2, 4, 5, 6, 7, 10}

...and look at the differences!


In [5]:
set2.difference(set1)


Out[5]:
{1, 6}

In [6]:
set1.difference(set2)


Out[6]:
{3, 8, 9}

See https://en.wikibooks.org/wiki/Python_Programming/Sets for more information about sets!


In [7]:
# Intersection
set1 & set2


Out[7]:
{2, 4, 5, 7, 10}

In [8]:
# Union
set1 | set2


Out[8]:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

In [9]:
# Difference
(set1 - set2) | (set2 - set1)


Out[9]:
{1, 3, 6, 8, 9}

In [10]:
# Difference method 2
(set1 | set2) - (set1 & set2)


Out[10]:
{1, 3, 6, 8, 9}

In [ ]: